from django.views import View

from User.models import Msg
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequiredUser


class MsgView(LoginRequiredUser, View):
    """ 消息 """

    def get(self, request):
        """ 查询 """
        limit = int(request.GET.get('limit', 10))
        page = int(request.GET.get('page', 1))

        user = request.user.user
        msgs = Msg.objects.filter(user=user).order_by('-createTime')
        result = []

        pages = {
            "total": msgs.count(),
            "limit": limit,
            "page": page
        }
        for msg in msgs[(page - 1) * limit:page * limit]:
            result.append(msg.Info())
        return Res.Json(Res.OK, result=result, pages=pages)

    def put(self, request):
        """ 已读 """
        id = request.GET.get('id')

        user = request.user.user
        Msg.Sign(user, id)
        return Res.Json(Res.OK)
